package com.x25175.file.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.x25175.file.Vo.LayuiTableVo;
import com.x25175.file.Vo.ResponseVO;
import com.x25175.file.constant.ImgPrefix;
import com.x25175.file.entity.Picture;
import com.x25175.file.entity.Student;
import com.x25175.file.service.PictureService;
import com.x25175.file.service.StudentService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author 徐佳辉
 * @date 2020/11/21 17:02
 */
@Data
@Controller
@Slf4j
public class PictureController {

    public static final String IMG_FIX = ImgPrefix.IMG_PREFIX;
    @Autowired
    private StudentService studentService;
    @Value("${pictureurl}")
    private String url;
    @Autowired
    private PictureService pictureService;

    /**
     * 上传或者更新图片
     *
     * @param file
     * @param studentId
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResponseVO upload(@RequestParam("file") MultipartFile file, Integer studentId) throws IOException {
        //上传到本地，url放到对应student表，返回url吧
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 新文件名
        fileName = studentId + suffixName;
        File dest = new File(url + fileName);

        Student student = studentService.selectByStudentId(studentId);
        if (student.getPicture() != null) {
            //获取图片路径
            String picture = student.getPicture();
            log.info(picture);
            //磁盘路径
            String s = picture.replaceFirst(IMG_FIX, url);
            //删除磁盘图片
            boolean b = deleteDiskPict(s);
            //不管成不成功后面都要更新
        }
        // 传到本地
        if (dest.exists()) {
            file.transferTo(dest);
        } else {
            dest.mkdirs();
            file.transferTo(dest);
        }
        //更新数据库
        student.setUpdateTime(new Date());
        student.setPicture(IMG_FIX + fileName);
        studentService.updateDynamic(student);

        String Url = IMG_FIX + fileName;
        //url在msg里面
        return ResponseVO.ok(Url);

    }

    /**
     * 删除图片
     *
     * @param s
     * @return
     */
    public boolean deleteDiskPict(String s) {
        File file = new File(s);
        boolean delete = file.delete();
        return delete;

    }

    /**
     * 删除图片
     *
     * @param studentId
     * @return
     * @throws IOException
     */
    @PostMapping("/delPic")
    @ResponseBody
    public ResponseVO upload(Integer studentId) throws IOException {

        log.info("studentId:{}", studentId);
        Student student = studentService.selectByStudentId(studentId);
        String picture = student.getPicture();
        if (StringUtils.isBlank(picture)) {
            return ResponseVO.error("没有图片");
        }
        log.info(picture);
        //磁盘路径
        String s = picture.replaceFirst(IMG_FIX, url);
        //删除磁盘图片
        boolean b = deleteDiskPict(s);
        student.setUpdateTime(new Date());
        student.setPicture(null);
        boolean b1 = studentService.updateDynamicExcluePic(student);
        return b1 ? ResponseVO.ok("删除成功") : ResponseVO.error("删除出现问题");


    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadOnlyPic")
    @ResponseBody
    public ResponseVO uploadp(@RequestParam("file") MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 新文件名使用纳秒作为文件名
        fileName = System.nanoTime() + suffixName;
        File dest = new File(url + fileName);

        Picture picture = new Picture();
        picture.setUrl(IMG_FIX + fileName);
        picture.setCreateTime(new Date());
        boolean insert = pictureService.insert(picture);

        // 传到本地
        if (dest.exists()) {
            file.transferTo(dest);
        } else {
            dest.mkdirs();
            file.transferTo(dest);
        }

        return ResponseVO.ok("上传成功");


    }

    /**
     * layui数据表格
     * 类型默认get
     * 返回分页数据
     *
     * @param page
     * @param limit
     * @return 返回格式 默认
     * {
     * "code":0
     * "msg":""
     * "count":总数
     * "data":[{},{}]
     * }
     */
    @GetMapping("/picturelist")
    @ResponseBody
    public LayuiTableVo list(int page, int limit) {
        PageHelper.startPage(page, limit);
        PageInfo<Picture> pageInfo = new PageInfo<>(pictureService.list());


        return LayuiTableVo.ok(pageInfo.getList(), (int) pageInfo.getTotal());
    }


    @PostMapping("/deletepic")
    @ResponseBody
    public ResponseVO deletep(@RequestBody List<Picture> pictureList) {
        log.info("picturelist{}", pictureList);

        for (Picture picture : pictureList) {
            String url = picture.getUrl();
            boolean b = pictureService.deleteImgByDataUrl(url);

        }

        int i = pictureService.deleteByPictureList(pictureList);
        log.info("删除:[{}]条", i);
        return ResponseVO.ok("删除成功");
    }


}
